import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

// 消息类型
export interface Message {
  id: string
  senderId: string
  receiverId: string
  content: string
  type: 'text' | 'image' | 'file' | 'emoji'
  timestamp: Date
  status: 'sending' | 'sent' | 'delivered' | 'read'
}

// 会话信息
export interface Conversation {
  id: string
  participantId: string
  participantName: string
  participantAvatar: string
  lastMessage?: Message
  unreadCount: number
  isOnline: boolean
  lastSeen?: Date
}

// 聊天状态管理
export const useChatStore = defineStore('chat', () => {
  const conversations = ref<Conversation[]>([])
  const messages = ref<Record<string, Message[]>>({})
  const activeConversationId = ref<string | null>(null)
  
  // 当前活跃的会话
  const activeConversation = computed(() => {
    if (!activeConversationId.value) return null
    return conversations.value.find(conv => conv.id === activeConversationId.value) || null
  })
  
  // 当前会话的消息
  const currentMessages = computed(() => {
    if (!activeConversationId.value) return []
    return messages.value[activeConversationId.value] || []
  })
  
  // 总未读消息数
  const totalUnreadCount = computed(() => {
    return conversations.value.reduce((total, conv) => total + conv.unreadCount, 0)
  })
  
  // 设置活跃会话
  const setActiveConversation = (conversationId: string) => {
    activeConversationId.value = conversationId
    // 标记消息为已读
    markMessagesAsRead(conversationId)
  }
  
  // 添加或更新会话
  const addOrUpdateConversation = (conversation: Conversation) => {
    const existingIndex = conversations.value.findIndex(conv => conv.id === conversation.id)
    if (existingIndex >= 0) {
      conversations.value[existingIndex] = conversation
    } else {
      conversations.value.unshift(conversation)
    }
  }
  
  // 发送消息
  const sendMessage = (content: string, receiverId: string, type: Message['type'] = 'text') => {
    const message: Message = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      senderId: 'current-user', // 这里应该从用户store获取
      receiverId,
      content,
      type,
      timestamp: new Date(),
      status: 'sending'
    }
    
    // 添加消息到对应会话
    const conversationId = getConversationId('current-user', receiverId)
    if (!messages.value[conversationId]) {
      messages.value[conversationId] = []
    }
    messages.value[conversationId].push(message)
    
    // 更新会话的最后消息
    const conversation = conversations.value.find(conv => conv.id === conversationId)
    if (conversation) {
      conversation.lastMessage = message
    }
    
    // 模拟发送成功
    setTimeout(() => {
      message.status = 'sent'
      // 模拟对方收到消息
      setTimeout(() => {
        message.status = 'delivered'
      }, 500)
    }, 1000)
    
    return message
  }
  
  // 接收消息
  const receiveMessage = (message: Message) => {
    const conversationId = getConversationId(message.senderId, message.receiverId)
    
    if (!messages.value[conversationId]) {
      messages.value[conversationId] = []
    }
    messages.value[conversationId].push(message)
    
    // 更新或创建会话
    let conversation = conversations.value.find(conv => conv.id === conversationId)
    if (!conversation) {
      conversation = {
        id: conversationId,
        participantId: message.senderId,
        participantName: `用户${message.senderId}`,
        participantAvatar: '/default-avatar.png',
        unreadCount: 0,
        isOnline: true
      }
      conversations.value.unshift(conversation)
    }
    
    conversation.lastMessage = message
    
    // 如果不是当前活跃会话，增加未读数
    if (activeConversationId.value !== conversationId) {
      conversation.unreadCount++
    }
  }
  
  // 标记消息为已读
  const markMessagesAsRead = (conversationId: string) => {
    const conversation = conversations.value.find(conv => conv.id === conversationId)
    if (conversation) {
      conversation.unreadCount = 0
    }
    
    // 标记消息为已读
    const conversationMessages = messages.value[conversationId]
    if (conversationMessages) {
      conversationMessages.forEach(msg => {
        if (msg.status === 'delivered') {
          msg.status = 'read'
        }
      })
    }
  }
  
  // 获取会话ID（基于参与者ID生成唯一标识）
  const getConversationId = (userId1: string, userId2: string) => {
    return [userId1, userId2].sort().join('-')
  }
  
  // 删除会话
  const deleteConversation = (conversationId: string) => {
    const index = conversations.value.findIndex(conv => conv.id === conversationId)
    if (index >= 0) {
      conversations.value.splice(index, 1)
      delete messages.value[conversationId]
      
      if (activeConversationId.value === conversationId) {
        activeConversationId.value = null
      }
    }
  }
  
  // 清空聊天记录
  const clearMessages = (conversationId: string) => {
    messages.value[conversationId] = []
    const conversation = conversations.value.find(conv => conv.id === conversationId)
    if (conversation) {
      conversation.lastMessage = undefined
      conversation.unreadCount = 0
    }
  }
  
  // 初始化模拟数据
  const initMockData = () => {
    const mockConversations: Conversation[] = [
      {
        id: 'conv-1',
        participantId: 'user-1',
        participantName: '张三',
        participantAvatar: '/avatars/user1.jpg',
        unreadCount: 2,
        isOnline: true,
        lastMessage: {
          id: 'msg-1',
          senderId: 'user-1',
          receiverId: 'current-user',
          content: '你好，最近怎么样？',
          type: 'text',
          timestamp: new Date(Date.now() - 1000 * 60 * 5),
          status: 'delivered'
        }
      },
      {
        id: 'conv-2',
        participantId: 'user-2',
        participantName: '李四',
        participantAvatar: '/avatars/user2.jpg',
        unreadCount: 0,
        isOnline: false,
        lastSeen: new Date(Date.now() - 1000 * 60 * 30),
        lastMessage: {
          id: 'msg-2',
          senderId: 'current-user',
          receiverId: 'user-2',
          content: '好的，明天见！',
          type: 'text',
          timestamp: new Date(Date.now() - 1000 * 60 * 60),
          status: 'read'
        }
      }
    ]
    
    conversations.value = mockConversations
    
    // 初始化消息
    messages.value = {
      'conv-1': [
        {
          id: 'msg-1-1',
          senderId: 'user-1',
          receiverId: 'current-user',
          content: '你好！',
          type: 'text',
          timestamp: new Date(Date.now() - 1000 * 60 * 10),
          status: 'read'
        },
        {
          id: 'msg-1-2',
          senderId: 'current-user',
          receiverId: 'user-1',
          content: '你好，有什么事吗？',
          type: 'text',
          timestamp: new Date(Date.now() - 1000 * 60 * 8),
          status: 'read'
        },
        {
          id: 'msg-1-3',
          senderId: 'user-1',
          receiverId: 'current-user',
          content: '你好，最近怎么样？',
          type: 'text',
          timestamp: new Date(Date.now() - 1000 * 60 * 5),
          status: 'delivered'
        }
      ],
      'conv-2': [
        {
          id: 'msg-2-1',
          senderId: 'current-user',
          receiverId: 'user-2',
          content: '明天的会议准备好了吗？',
          type: 'text',
          timestamp: new Date(Date.now() - 1000 * 60 * 120),
          status: 'read'
        },
        {
          id: 'msg-2-2',
          senderId: 'user-2',
          receiverId: 'current-user',
          content: '准备好了，资料都整理完了',
          type: 'text',
          timestamp: new Date(Date.now() - 1000 * 60 * 90),
          status: 'read'
        },
        {
          id: 'msg-2-3',
          senderId: 'current-user',
          receiverId: 'user-2',
          content: '好的，明天见！',
          type: 'text',
          timestamp: new Date(Date.now() - 1000 * 60 * 60),
          status: 'read'
        }
      ]
    }
  }

  return {
    conversations,
    messages,
    activeConversationId,
    activeConversation,
    currentMessages,
    totalUnreadCount,
    setActiveConversation,
    addOrUpdateConversation,
    sendMessage,
    receiveMessage,
    markMessagesAsRead,
    deleteConversation,
    clearMessages,
    initMockData
  }
})
